package com.ltb.speedlottery;

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.ltb.speedlottery.adapter.CommonAdapter;
import com.ltb.speedlottery.adapter.ViewHolder;
import com.ltb.speedlottery.bean.Data;
import com.ltb.speedlottery.bean.History;
import com.ltb.speedlottery.utils.Computer;
import com.ltb.speedlottery.utils.NotifyUtils;
import com.qmuiteam.qmui.widget.QMUIAnimationListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.iwgang.countdownview.CountdownView;
import io.realm.RealmList;

public class MainActivity extends AppCompatActivity implements Response.Listener<String>, Response.ErrorListener {
    private String LOTTERY_ID = "120";//3分六合彩
//    private String LOTTERY_ID = "166";//1分六合彩
    private final int DEFAULT_OFFSET = 150;
    private final String URL ="https://www.v8816.com/eapi/get_lottery_data?";
    private CountdownView mCountDownView;
    private QMUIAnimationListView mListView;
    private SwipeRefreshLayout mRefreshLayout;
    private TextView mFirstMix6TV;
    private TextView mFirstCoupleTV;
    private TextView mFirstSemiSequenceTV;
    private TextView mSecondMix6TV;
    private TextView mSecondCoupleTV;
    private TextView mSecondSemiSequenceTV;
    private TextView m3thdMix6TV;
    private TextView m3thdCoupleTV;
    private TextView m3thdSemiSequenceTV;
    private RequestQueue mQueue = null;
    private  CommonAdapter<Data> mAdapter;
    private List<Data> mDates = new ArrayList<>();
    private ArrayList<Integer> mFirstItems = new ArrayList();
    private ArrayList<Integer> mSecondItems = new ArrayList();
    private ArrayList<Integer> mThirdItems = new ArrayList();
    private int MAX_REQUEST_COUNT = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        queryData(DEFAULT_OFFSET);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mHandler != null){
            if(mHandler.hasMessages(1)){
                mHandler.removeMessages(1);
            }

            if(mHandler.hasMessages(2)){
                mHandler.removeMessages(2);
            }
        }
    }

    private void init(){
//        mH5ContentTV = (TextView) findViewById(R.id.tv_html_content);
        mListView= (QMUIAnimationListView)findViewById(R.id.lv_history);
        mRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.refresh_layout);
        mCountDownView = (CountdownView) findViewById(R.id.cv_countdownView);
        mFirstMix6TV = (TextView) findViewById(R.id.tv_first_mix6);
        mFirstCoupleTV = (TextView) findViewById(R.id.tv_first_couple);
        mFirstSemiSequenceTV = (TextView) findViewById(R.id.tv_first_semi_sequence);
        mSecondMix6TV = (TextView) findViewById(R.id.tv_second_mix6);
        mSecondCoupleTV = (TextView) findViewById(R.id.tv_second_couple);
        mSecondSemiSequenceTV = (TextView) findViewById(R.id.tv_second_semi_sequence);
        m3thdMix6TV = (TextView) findViewById(R.id.tv_3thd_mix6);
        m3thdCoupleTV = (TextView) findViewById(R.id.tv_3thd_couple);
        m3thdSemiSequenceTV = (TextView) findViewById(R.id.tv_3thd_semi_sequence);
        mCountDownView.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
            @Override
            public void onEnd(CountdownView cv) {
                queryData(1);
            }
        });
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                queryData(1);
            }
        });
        mQueue = Volley.newRequestQueue(this);
        mAdapter = new CommonAdapter<Data>(this, mDates, R.layout.item_history_layout){
            @Override
            public void convert(ViewHolder helper, Data item, int position) {
                helper.setText(R.id.tv_number, item.getNumber());
                helper.setText(R.id.tv_data_first, item.getDatas()[0]);
                helper.setText(R.id.tv_data_second, item.getDatas()[1]);
                helper.setText(R.id.tv_data_3thd, item.getDatas()[2]);
                helper.setText(R.id.tv_data_4thd, item.getDatas()[3]);
                helper.setText(R.id.tv_data_5thd, item.getDatas()[4]);
                StringBuilder sb = new StringBuilder();
                sb.append(analysisResult(item.getFirstThree()))
                        .append("  ").append(analysisResult(item.getMiddleThree()))
                        .append("  ").append(analysisResult(item.getPostThree()));
                helper.setText(R.id.tv_analysis_result, sb.toString());
                int coupleCount = Computer.dataAnalysisCouple(item.getIntData());
                if(coupleCount == 1){
                    helper.getView(R.id.tv_coupe).setVisibility(View.VISIBLE);
                } else {
                    helper.getView(R.id.tv_coupe).setVisibility(View.INVISIBLE);
                }
            }
        };
        findViewById(R.id.btn_one_minutes).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LOTTERY_ID = "166";
                mDates.clear();
                queryData(DEFAULT_OFFSET);
            }
        });

        findViewById(R.id.btn_three_minutes).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDates.clear();
                LOTTERY_ID = "120";
                queryData(DEFAULT_OFFSET);
            }
        });
        mListView.setAdapter(mAdapter);
        mFirstItems.add(0);
        mFirstItems.add(0);
        mFirstItems.add(0);
        mSecondItems.add(0);
        mSecondItems.add(0);
        mSecondItems.add(0);
        mThirdItems.add(0);
        mThirdItems.add(0);
        mThirdItems.add(0);
    }

    private void queryData(int offset){
        StringBuilder urlBuilder = new StringBuilder(URL);
        urlBuilder.append("lottery_id=").append(LOTTERY_ID).append("&offset=").append(offset);
        StringRequest stringRequest = new StringRequest(urlBuilder.toString(), this ,this);
        mQueue.add(stringRequest);
    }

    @Override
    public void onErrorResponse(VolleyError volleyError) {
//        mH5ContentTV.setText(volleyError.getMessage());
    }

    @Override
    public void onResponse(String result) {
        try {
            JSONObject jsonObject = new JSONObject(result);
            if(jsonObject!= null
                    &&jsonObject.has("code") && jsonObject.getInt("code") == 0
                    && jsonObject.has(LOTTERY_ID) || jsonObject.getString(LOTTERY_ID) != null){
                String json = jsonObject.getString(LOTTERY_ID);
                Gson gson = new Gson();
                final History history = gson.fromJson(json, History.class);
                if(null != history){
                    mRefreshLayout.setRefreshing(false);//设置不刷新
                    mCountDownView.stop();
                    //延迟５秒刷新数据　
                    mCountDownView.start((3+history.getNext().getRemain())*1000);

                    mListView.manipulate(new QMUIAnimationListView.Manipulator<CommonAdapter<Data>>() {
                        @Override
                        public void manipulate(CommonAdapter adapter) {
                            RealmList<Data> arrys = history.getData();
                            Data data = mAdapter.getItem(0);
                            if(data!= null){
                                String number = data.getNumber();
                                arrys = distinctData(Integer.parseInt(number), arrys);
                            }
                            if(arrys.size() > 0){
                                mDates.addAll(0, arrys);
                                adapter.notifyDataSetChanged();
                            }
                        }
                    });

//                    mAdapter.notifyDataSetChanged();
//                    StringBuilder sb = new StringBuilder();
//                    sb.append("结果:\n前三: ").append(analysisResult(history.getData().get(0).getFirstThree()))
//                    .append("\n中三: ").append(analysisResult(history.getData().get(0).getMiddleThree()))
//                    .append("\n后三: ").append(analysisResult(history.getData().get(0).getPostThree()));
//                    mH5ContentTV.setText(sb);
//                    showLastAnalysisResult();
                    new MyTask().execute();

                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    };

    private String analysisResult(int[] datas){
        int [] resultArray = Computer.dataAnalysis(datas);
        String value = null;
        if(resultArray[0] == 1){
            value = "对子";
        }else if(resultArray[0] == 2){
            value = "豹子";
        }else if(resultArray[1] == 1){
            value = "半顺";
        }else if(resultArray[1] == 2){
            value = "顺子";
        }else{
            value = "杂六";
        }
        return value;
    }

    private RealmList<Data> distinctData(int firstNumber ,RealmList<Data> datas){
        if(firstNumber == 0){
            return datas;
        }
        if(datas != null && datas.size() ==1){
            int number =Integer.parseInt(datas.get(0).getNumber());
            if(number == firstNumber){
                datas.clear();
                if(mHandler.hasMessages(2)){
                    mHandler.removeMessages(2);
                }
                mHandler.sendEmptyMessageAtTime(2, 1000);
                return datas;
            }
        }
        MAX_REQUEST_COUNT = 0;
        List<Integer> remove = new ArrayList<>();
        for(Data item: datas){
            if(firstNumber>= Integer.parseInt(item.getNumber())){
                remove.add(datas.indexOf(item));
            }
        }
        int size = remove.size();
        if(size > 0){
            for(int i= 0; i < size; i++){
                if(i < datas.size()){
                    datas.remove(i);
                }
            }
        }
        return datas;
    }

    private class MyTask extends AsyncTask{
        @Override
        protected Object doInBackground(Object[] objects) {
            int size = mDates.size();
            for(int i=size-1; i>=0; i--){
                Data item = mAdapter.getItem(i);
                if(item != null){
                    analysisResult(item.getFirstThree(), mFirstItems);
                    analysisResult(item.getMiddleThree(), mSecondItems);
                    analysisResult(item.getPostThree(), mThirdItems);
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            showLastAnalysisResult();
        }
    };

    private void showLastAnalysisResult(){

        mFirstMix6TV.setText(getMix6(mFirstItems.get(0)));
        mFirstCoupleTV.setText(getCouple(mFirstItems.get(1)));
        mFirstSemiSequenceTV.setText(getSemiSequence(mFirstItems.get(2)));
        mSecondMix6TV.setText(getMix6(mSecondItems.get(0)));
        mSecondCoupleTV.setText(getCouple(mSecondItems.get(1)));
        mSecondSemiSequenceTV.setText(getSemiSequence(mSecondItems.get(2)));
        m3thdMix6TV.setText(getMix6(mThirdItems.get(0)));
        m3thdCoupleTV.setText(getCouple(mThirdItems.get(1)));
        m3thdSemiSequenceTV.setText(getSemiSequence(mThirdItems.get(2)));

    }

    private SpannableString getMix6(int count){
        String str=String.format(getString(R.string.analysis_mix6), String.valueOf(count));
        SpannableString spannable = new SpannableString(str);
        if(count <= -7){
            spannable.setSpan(new ForegroundColorSpan(Color.parseColor("#EB0000")), 3, 3 + String.valueOf(count).length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

            if(mHandler.hasMessages(1)){
                mHandler.removeMessages(1);
            }
            mHandler.sendEmptyMessageAtTime(1, 1000);
        }
        return spannable;
    }

    private SpannableString getCouple(int count){
        String str=String.format(getString(R.string.analysis_couple), String.valueOf(count));
        SpannableString spannable = new SpannableString(str);
        if(count <= -7){
            spannable.setSpan(new ForegroundColorSpan(Color.parseColor("#EB0000")), 3, 3 + String.valueOf(count).length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            if(mHandler.hasMessages(1)){
                mHandler.removeMessages(1);
            }
            mHandler.sendEmptyMessageAtTime(1, 1000);
        }
        return spannable;
    }

    private SpannableString getSemiSequence(int count){
        String str=String.format(getString(R.string.analysis_semi_sequence), String.valueOf(count));
        SpannableString spannable = new SpannableString(str);
        if(count <= -3){
            spannable.setSpan(new ForegroundColorSpan(Color.parseColor("#EB0000")), 3, 3 + String.valueOf(count).length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            if(mHandler.hasMessages(1)){
                mHandler.removeMessages(1);
            }
            mHandler.sendEmptyMessageAtTime(1, 1000);
        }
        return spannable;
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    NotifyUtils.showNotify(MainActivity.this);
                    break;
                case 2:
                    if(MAX_REQUEST_COUNT <=3 ){
                        queryData(1);
                        MAX_REQUEST_COUNT++;
                    }
                    break;
            }
        }
    };


    private void analysisResult(int[] datas, List<Integer> list){
        int [] resultArray = Computer.dataAnalysis(datas);
        int cacheMix6 =list.get(0);
        int cacheCouple = list.get(1);
        int cacheSemiSequence = list.get(2);
        if(resultArray[0] == 1){
            if(cacheMix6 > 0){
                cacheMix6=0;
            }
            cacheMix6--;
            if(cacheCouple <0){
                cacheCouple = 0;
            }
            cacheCouple++;
            if(cacheSemiSequence > 0){
                cacheSemiSequence = 0;
            }
            cacheSemiSequence--;

        }else if(resultArray[0] == 2 || resultArray[1] == 1 || resultArray[1] == 2){
            if(cacheMix6 > 0){
                cacheMix6 = 0;
            }
            cacheMix6--;
            if(cacheCouple > 0){
                cacheCouple = 0;
            }
            cacheCouple--;

            if(resultArray[1] == 1|| resultArray[1] == 2){
                if(cacheSemiSequence < 0){
                    cacheSemiSequence = 0;
                }
                cacheSemiSequence++;
            } else {
                if(cacheSemiSequence > 0){
                    cacheSemiSequence = 0;
                }
                cacheSemiSequence--;
            }

        } else{
            if(cacheMix6 <0){
                cacheMix6 = 0;
            }
            cacheMix6++;
            if(cacheCouple > 0){
                cacheCouple = 0;
            }
            cacheCouple--;
            if(cacheSemiSequence > 0){
                cacheSemiSequence = 0;
            }
            cacheSemiSequence--;
        }
        list.set(0, cacheMix6);
        list.set(1, cacheCouple);
        list.set(2, cacheSemiSequence);
//        Log.d("Tianbing", " cacheMix6="+cacheMix6 +" cacheCouple="+cacheCouple);
    }
}
